package handler

import (
	"demo/internal/service"
	"demo/pkg/response"
	"strconv"

	"github.com/gin-gonic/gin"
)

type UserHandler struct {
	svc *service.UserService
}

func NewUserHandler(svc *service.UserService) *UserHandler {
	return &UserHandler{
		svc: svc,
	}
}

// @Summary		分页查询用户列表
// @Description	根据昵称模糊查询并分页返回用户列表
// @Tags			用户管理
// @Accept			json
// @Produce		json
// @Param			nickname	query		string	false	"用户昵称（模糊查询）"
// @Param			page		query		integer	false	"页码（默认1）"
// @Param			size		query		integer	false	"每页大小（默认10）"
// @Success		200			{object}	response.Response{data=object{total=integer,users=[]model.User}}	"查询成功"
// @Failure		500			{object}	response.Response	"服务器内部错误"
// @Router			/api/users [get]
// @Security		BearerAuth
func (h *UserHandler) ListUsers(c *gin.Context) {
	nickname := c.Query("nickname")
	page := 1
	size := 10

	if pageStr := c.Query("page"); pageStr != "" {
		if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
			page = p
		}
	}
	if sizeStr := c.Query("size"); sizeStr != "" {
		if s, err := strconv.Atoi(sizeStr); err == nil && s > 0 {
			size = s
		}
	}

	users, total, err := h.svc.ListUsers(nickname, page, size)
	if err != nil {
		response.InternalServerError(c, err.Error())
		return
	}

	response.Success(c, gin.H{
		"total": total,
		"users": users,
	}, "查询成功")
}
